﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.GridType;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.Handler.GridType
{
    public class CreateGridtypeHandler : IRequestHandler<CreateGridtypeCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<GridTypeModel> gridTypeRepo;
        private readonly IMapper mapper;

        public CreateGridtypeHandler(IBaseRepository<GridTypeModel> gridTypeRepo,IMapper mapper)
        {
            this.gridTypeRepo = gridTypeRepo;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(CreateGridtypeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            //把请求命令对象转成网格类型实体
            var gridTypeModel = mapper.Map<GridTypeModel>(request); // request:请求命令对象
            gridTypeModel.Id = YitIdHelper.NextId();
            var r = await gridTypeRepo.CreateAsync(gridTypeModel);
            if (r > 0)
            {
                res.Msg = "添加网格类型成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else {
                res.Msg = "添加网格类型失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }
            return res;

        }
    }
}
